package com.lagou.server;

import com.lagou.common.JSONSerializer;
import com.lagou.common.RpcDecoder;
import com.lagou.handler.RpcServerHandler;
import com.lagou.pojo.RpcRequest;
import com.lagou.service.IUserService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements IUserService {

    public String sayHello(String word) {
        System.out.println("调用成功--参数：" + word);
        return "调用成功--参数：" + word;
    }

    public String invoke(RpcRequest rpcRequest) {
        return "success";
    }


    public static void startServer(String hostName, int port){
        try {
            NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(eventLoopGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new StringEncoder());
                            p.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                            p.addLast(new RpcServerHandler());
                        }
                    });

            bootstrap.bind(hostName, port).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
